﻿CREATE PROCEDURE [dbo].[usp_select_Fault_Count_By_Error_Type]
(
	   @StartDate			datetime        =	null 
	   ,@EndDate			datetime		=	null  
	   ,@application        varchar(512)	=	null   
	   ,@Debug				bit             =	0
)
AS

/****************************************************************************
Name: usp_select_Fault_Count_By_Error_Type.sql
*****************************************************************************/
SET NOCOUNT ON;

-- Bootstrap
DECLARE @DebugPrefix       varchar(10);
DECLARE @ErrorCode         int;

SET @ErrorCode          = 0;
SET @DebugPrefix        = '>>> DEBUG: ';

SET @EndDate = DATEADD(day,1,@EndDate)

-- Print parameters
IF (@Debug > 0)
BEGIN
	PRINT '@StartDate = ' + CAST (@StartDate as varchar)
	PRINT '@EndDate = ' + CAST (@EndDate as varchar)
END;


-- Possible SQL injection issue, but since this Interal app only no worries.

--DECLARE @SQL varchar(1600)

--	SET @SQL ='SELECT COUNT(*) as [FaultCount], [ErrorType] as [FaultType], null as [Application] FROM dbo.[Fault] WHERE [DateTime] 
--BETWEEN N''' +CAST( @StartDate as varchar) +''' AND N''' + CAST(@EndDate as varchar) + ''' AND [application] in (' + @application + ')'
--+ 'GROUP BY [ErrorType] 
--ORDER BY [ErrorType]'

--	EXEC(@SQL)

SELECT
	COUNT(*) as 'FaultCount',
	af.[ErrorType] as 'FaultType',
	'' as 'Application'

FROM dbo.vw_AggregatedFaults af

WHERE 
	af.[Application] IN(SELECT [Application] FROM [udf_SplitApplications](@application))
   AND   
   af.[TrueDateTime] between @StartDate and @EndDate

GROUP BY af.[ErrorType]


-- CHECK FOR ERROR
SET @ErrorCode = @@Error;
IF (@ErrorCode <> 0) GOTO ERROR_HANDLER;
			
RETURN 0;

-- Handles errors.
ERROR_HANDLER:
IF (@ErrorCode <> 0)
BEGIN
    IF (@Debug > 0) 
		BEGIN
			PRINT @DebugPrefix + 'Error Code = ' + CAST(@ErrorCode AS varchar(10)) + ' occurred.';
			RETURN @ErrorCode
		END

    -- Don't return any evidence of what specific error occurred, i.e. 
    -- we want to ward off potential hackers.
    RETURN 1;
END;

SET NOCOUNT OFF;
